from kubernetes import client, config
from os import path
import yaml

class k8sapi:
    def k8s_conn(self):
        config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
        conn = client.CoreV1Api()
        return conn

    def namespaces(self):
        # 列出 namespaces
        conn = self.k8s_conn()
        ret = conn.list_pod_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s   %s      %s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    def services(self):
        # 列出所有的services
        list_svc = []
        conn = self.k8s_conn()
        ret = conn.list_service_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s   %s      %s      %s      %s " % (i.kind, i.metadata.namespace, i.metadata.name, i.spec.cluster_ip, i.spec.ports))
            list_service = {}
            service_name = i.metadata.name
            type = i.kind
            namespace = i.metadata.namespace
            cluster_ip = i.spec.cluster_ip
            port = i.spec.ports
            list_service['service_name'] = service_name
            list_service['type'] = type
            list_service['namespace'] = namespace
            list_service['cluster_ip'] = cluster_ip
            list_service['port'] = port
            list_svc.append(list_service)
        return list_svc
    def pods(self):
        # 列出所有的pod
        list_pods = []
        conn = self.k8s_conn()
        ret = conn.list_pod_for_all_namespaces(watch=False)
        for i in ret.items:
            podsinfo = {}
            podip = i.status.pod_ip
            ns = i.metadata.namespace
            pod_name = i.metadata.name
            podsinfo['podip'] = podip
            podsinfo['ns'] = ns
            podsinfo['pod_name'] = pod_name
            list_pods.append(podsinfo)
            # print("%s   %s      %s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
        return list_pods
    def create(self):
        config.load_kube_config()
        with open(path.join(path.dirname(__file__), "/root/deploy.yaml")) as f:
            dep = yaml.safe_load(f)
            k8s_apps_v1 = client.AppsV1Api()
            resp = k8s_apps_v1.create_namespaced_deployment(
                body=dep, namespace="default")
            print("Deployment created. status='%s'" % resp.metadata.name)
    def delete(self):
        config.load_kube_config()
        k8s_core_v1 = client.CoreV1Api()
        resp = k8s_core_v1.delete_namespaced_pod(namespace="default", name='nginx-pod')
        print("delete Pod ")
    # def create_ns(self):
    #     conn = self.k8s_conn()
    #     ns = client.V1Namespace()
    #     ns.metadata = client.V1ObjectMeta(name="test-ns")
    #     conn.create_namespace(body=ns)
    #     print("create ns")

# if __name__ == '__main__':
#     myk8s = k8sapi()
#     #myk8s.pods()
#     myk8s.create_ns()
#     myk8s.namespaces()
#     myk8s.services()